package applauncher;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import vrann.dataformats.json.*;

public class Programm {
	
	protected WorkerResources resource = new WorkerResources();
	
	protected String name;
	
	protected String path;
	
	protected String options;

	public Programm(String programmName)
	{
		name = programmName;
	}
	
	public void install(String options, byte[] binary) throws IOException
	{
		saveBinary(binary);	
		JsonElement programmJson = getJson();
		resource.getDocumentFromJson(programmJson);
	}
	
	protected void saveBinary(byte[] binary) throws IOException
	{
		File filePath = Config.getProgramDir(name);
		if (!filePath.exists()) {
			filePath.mkdir();
		}
		File programmPath = new File(filePath, name);
		FileOutputStream writter = new FileOutputStream(programmPath);
		writter.write(binary);
		path = programmPath.getAbsolutePath();
	}
	
	protected JsonElement getJson() throws Exception
	{
		JsonHash programmHash = new JsonHash();
		programmHash.put("name", new JsonString(name));
		programmHash.put("path", new JsonString(path));
		programmHash.put("options", JsonElement.initFromString(options));
		return programmHash;
	}
}
